﻿@using System.Timers
@using Microsoft.AspNetCore.Components.Web;
<div tabindex="0" 
    onclick="@((MouseEventArgs e) => HandleClick(e))"
    @oncontextmenu="OnContextMenu"
    @onblur="OnBlur"
    @onmouseup="HandleMouseUp"
    @oncontextmenu:preventDefault="true">
    <Tooltip Title="More options"><label>&vellip;</label></Tooltip>
</div>

<CascadingValue Value="this">
    <div class="contextmenu"
         style="@($"z-index:1000; visibility:{GetVisibility()};")">
        @if (_show)
        {
            <ul class="contextmenuitems">
                @foreach (ContextMenuItem it in Items)
                {
                    <li tabindex="@GetTabIndex()" class="contextmenuitem" onclick="@(async () => it.Click())">
                        @if (string.IsNullOrEmpty(it.Icon) == false)
                        {
                            <div class="@it.Icon" style="padding-right: 5px;"></div>
                        }
                        @it.Text
                    </li>
                }
            </ul>
        }
    </div>
    @ChildContent
</CascadingValue>

@code {
    string GetVisibility()
    {
        if (_show)
        {
            return "visible";
        }
        return "hidden";
    }
    protected bool _show;

    /// <summary>
    /// Contect menu items.
    /// </summary>
    List<ContextMenuItem> Items = new List<ContextMenuItem>();

    int _index = 0;
    System.Timers.Timer _timer = new System.Timers.Timer();

    private string GetTabIndex()
    {
        ++_index;
        return _index.ToString();
    }


    void HandleClick(MouseEventArgs args)
    {
        if (args.Button == 0)
        {
            Show();
        }
    }

    void OnContextMenu(MouseEventArgs args)
    {
        Show();
    }

    void HandleMouseUp(MouseEventArgs args)
    {
        //        Show();
        _timer.Stop();
    }

    void OnBlur(FocusEventArgs args)
    {
        _timer.Interval = 300;
        _timer.AutoReset = true;
        _timer.Elapsed += TimerElapsed;
        _timer.Start();
    }

    private void TimerElapsed(object? sender, ElapsedEventArgs e)
    {
        Hide();
        _timer.Stop();
    }

    [Parameter]
    public RenderFragment? ChildContent { get; set; }

    /// <summary>
    /// Show contect menu.
    /// </summary>
    internal void Show()
    {
        _show = true;
        StateHasChanged();
    }

    /// <summary>
    /// Hide contect menu.
    /// </summary>
    internal void Hide()
    {
        if (_show)
        {
            _show = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// Add new menu item.
    /// </summary>
    /// <param name="menu">New menu item.</param>
    internal void AddMenuItem(ContextMenuItem menu)
    {
        Items.Add(menu);
    }
}
